﻿using System.Collections.Generic;
using Microsoft.SharePoint;

namespace TennisSite.FeatureReceivers
{
    public class WebPartsFeatureReceiver : SPFeatureReceiver
    {
        private const string TENNIS_SITE_URL_PROPERTY_NAME = "TENNIS_SITE_WEB_URL";
        private const string PLAYERS_WEBPART_NAME_PROPERTY_NAME = "PLAYERS_WEBPART_NAME";
        private const string WEBPART_FIELD_PROPERTY_NAME = "WEBPART_NAME_FIELD_NAME";

        private string tennisSiteWebUrl;
        private string playersWebPartName;
        private string webPartFieldName;

        public override void FeatureUninstalling(SPFeatureReceiverProperties properties)
        {
        }

        public override void FeatureInstalled(SPFeatureReceiverProperties properties)
        {
        }

        public override void FeatureDeactivating(SPFeatureReceiverProperties properties)
        {
            FillProperties(properties);

            SPWeb web = ((SPSite)properties.Feature.Parent).RootWeb;
            List<SPList> webPartGalleries = GetWebPartGalleries(web);
            FindAndRemovePlayersWebPart(webPartGalleries);

            web.Update();
        }

        private void FindAndRemovePlayersWebPart(List<SPList> galleries)
        {
            foreach (SPList webPartGallery in galleries)
            {
                foreach (SPListItem webPart in webPartGallery.Items)
                {
                    if (webPart[webPartFieldName].ToString() == playersWebPartName)
                    {
                        webPart.Delete();
                        webPartGallery.Update();
                        return;
                    }
                }
            }
        }

        private List<SPList> GetWebPartGalleries(SPWeb web)
        {
            List<SPList> galleries = new List<SPList>();

            foreach (SPList list in web.Lists)
            {
                if (list.BaseTemplate == SPListTemplateType.WebPartCatalog)
                {
                    galleries.Add(list);
                }
            }

            return galleries;
        }

        public override void FeatureActivated(SPFeatureReceiverProperties properties)
        {

        }

        private void FillProperties(SPFeatureReceiverProperties properties)
        {
            tennisSiteWebUrl = properties.Feature.Properties[TENNIS_SITE_URL_PROPERTY_NAME].Value;
            playersWebPartName = properties.Feature.Properties[PLAYERS_WEBPART_NAME_PROPERTY_NAME].Value;
            webPartFieldName = properties.Feature.Properties[WEBPART_FIELD_PROPERTY_NAME].Value;
        }
    }
}